<template>
  <div class="teacher-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" size="small" class="search-form">
        <el-form-item style="margin-bottom:0;margin-right:8px;">
          <el-input v-model="searchForm.tname" placeholder="教师关键字" style="width:120px;" />
        </el-form-item>
        <el-form-item style="margin-bottom:0;margin-right:8px;">
          <el-input v-model="searchForm.department" placeholder="系关键字" style="width:120px;" />
        </el-form-item>
        <el-form-item style="margin-bottom:0;margin-right:8px;">
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
        </el-form-item>
        <el-form-item style="margin-bottom:0;margin-right:8px;">
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
        <el-form-item style="margin-bottom:0;">
          <el-button type="success" :icon="Plus" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-card class="table-card">
    <el-table :data="tableData" :loading="tableLoading" border style="width: 100%" size="small">
  <el-table-column type="index" label="序号" width="60" align="center" />
  <el-table-column prop="teacher_number" label="工号/手机号" width="190" />
  <el-table-column prop="teacher_name" label="姓名" width="120" />
  <el-table-column prop="department_name" label="所属系" :min-width="200" show-overflow-tooltip />
  <el-table-column label="操作" fixed="right" width="160">
          <template #default="{ row }">
            <div style="display: flex; justify-content: space-around">
              <el-button size="small" :icon="Edit" @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" :icon="DeleteIcon" @click="handleDelete(row)"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.pageNo"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        size="small"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 添加/编辑对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="40%" class="form-dialog" modal-class="light-modal-mask">
      <el-form :model="dialogForm" label-width="120px" size="small">
        <el-form-item label="工号/手机号">
          <el-input v-model="dialogForm.teacher_number"></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="dialogForm.teacher_name"></el-input>
        </el-form-item>
        <el-form-item label="所属系">
          <el-select v-model="dialogForm.teacher_department_id" placeholder="请选择系">
            <el-option
              v-for="item in departmentList"
              :key="item.department_id"
              :label="item.department_name"
              :value="item.department_id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button size="small" @click="dialogVisible = false">取消</el-button>
          <el-button size="small" type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <BaseConfirmDialog
      :visible="confirmVisible"
      title="提示"
      :message="confirmMessage"
      confirm-text="确定"
      cancel-text="取消"
      @confirm="confirmDelete"
      @cancel="confirmVisible=false"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import {
  getTeacherAPI,
  addTeacherAPI,
  updateTeacherAPI,
  deleteTeacherAPI
} from '@/api/admin/teacher.js'
import { getFacultiesAPI } from '@/api/admin/faculties.js'
import BaseConfirmDialog from '@/components/BaseConfirmDialog.vue'
import { Search, Refresh, Plus, Edit, Delete as DeleteIcon } from '@element-plus/icons-vue'

// 搜索表单
const searchForm = reactive({
  tname: '',
  department: ''
})

// 表格数据
const tableData = ref([])
const tableLoading = ref(false)

// 分页
const pagination = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogForm = reactive({
  teacher_id: '',
  teacher_number: '',
  teacher_name: '',
  teacher_department_id: ''
})
const isEdit = ref(false)

// 系下拉列表
const departmentList = ref([])

// 获取教师数据
const fetchTeachers = async () => {
  const params = {
    pageNo: pagination.pageNo,
    pageSize: pagination.pageSize,
    ...searchForm
  }
  tableLoading.value = true
  try {
    const res = await getTeacherAPI(params)
    // 拦截器已返回 data 字段
    tableData.value = res?.list || []
    pagination.total = res?.total || 0
  } finally {
    tableLoading.value = false
  }
}

// 获取系数据
const fetchDepartments = async () => {
  const res = await getFacultiesAPI({ pageNo: 1, pageSize: 999 }) // 获取所有系
  departmentList.value = res?.list || []
}

onMounted(() => {
  fetchTeachers()
  fetchDepartments()
})

// 搜索
const handleSearch = () => {
  pagination.pageNo = 1
  fetchTeachers()
}

// 重置
const handleReset = () => {
  searchForm.tname = ''
  searchForm.department = ''
  pagination.pageNo = 1
  fetchTeachers()
}

// 添加
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '添加教师'
  Object.assign(dialogForm, {
    teacher_id: '',
    teacher_number: '',
    teacher_name: '',
    teacher_department_id: ''
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑教师'
  // department_id is not in teacher list response, need to find it from departmentList
  const department = departmentList.value.find(
    (item) => item.department_name === row.department_name
  )
  Object.assign(dialogForm, {
    teacher_id: row.teacher_id,
    teacher_number: row.teacher_number,
    teacher_name: row.teacher_name,
    teacher_department_id: department ? department.department_id : ''
  })
  dialogVisible.value = true
}

// 删除
const confirmVisible = ref(false)
const confirmMessage = ref('')
let pendingDeleteId = ''
const handleDelete = (row) => {
  pendingDeleteId = row.teacher_id
  confirmMessage.value = `确定要删除教师 "${row.teacher_name}" 吗？`
  confirmVisible.value = true
}
const confirmDelete = async () => {
  await deleteTeacherAPI({ teacher_id: pendingDeleteId })
  confirmVisible.value = false
  fetchTeachers()
}

// 提交表单
const handleSubmit = async () => {
  let res
  if (isEdit.value) {
    res = await updateTeacherAPI(dialogForm)
  } else {
    res = await addTeacherAPI(dialogForm)
  }
  // 成功消息已由响应拦截器统一处理
  dialogVisible.value = false
  fetchTeachers()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchTeachers()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.pageNo = val
  fetchTeachers()
}
</script>

<style lang="scss" scoped>
.teacher-container {
  padding: 8px 20px 20px 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.search-bar {
  display: flex;
  align-items: center;
  padding: 0;
  margin: 0 0 18px 0;
  background: none;
  border: none;
  box-shadow: none;
}
.search-form {
  display: flex;
  align-items: center;
  gap: 0;
  padding: 0;
  margin: 0;
}
.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 8px;
}
.search-form .el-input__wrapper,
.search-form .el-button {
  height: 26px !important;
  min-height: 26px !important;
  font-size: 13px;
}
.table-card {
  margin-top: 0;
}
.el-table {
  margin-top: 0;
}
.el-pagination {
  margin-top: 6px;
  display: flex;
  justify-content: center;
}
.el-pagination .el-pager li {
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  background: #fff;
  color: #606266;
  min-width: 32px;
  height: 32px;
  line-height: 32px;
  margin: 0 2px;
  font-size: 15px;
  cursor: pointer;
}
.el-pagination .el-pager li.active {
  background: #409eff;
  color: #fff;
  border-color: #409eff;
}
.table-card {
  flex: 1 1 0%;
  min-height: 0;
  display: flex;
  flex-direction: column;
  padding-top: 6px;
}
.table-card :deep(.el-card__body) {
  flex: 1 1 0%;
  min-height: 0;
  display: flex;
  flex-direction: column;
}
.table-card :deep(.el-table) {
  flex: 1 1 auto;
  overflow: auto;
}
.el-pagination {
  margin-top: 8px;
  display: flex;
  justify-content: center;
}
</style>
